<template>
  <div class="table-container">
    <a-table size="small" :columns="columns" :data-source="prop.tableList" :pagination="false">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'pic'">
          <a-image
            v-if="record.draw?.pic && record.draw.pic.length > 0"
            :width="50"
            :src="record.draw.pic[0]"
            :preview="{
              src: record.draw.pic[0],
            }"
          />
          <span v-else>-</span>
        </template>
        <template v-if="column.key === 'subTitle'">
          <a-tag :color="SubTypeEnum[record.draw.subTitle as '1' | '2' | '3' | '4'].color">{{
            SubTypeEnum[record.draw.subTitle as '1' | '2' | '3' | '4'].value
          }}</a-tag>
        </template>
        <!-- 可编辑：总数量 -->
        <template v-if="column.key === 'num'">
          <template v-if="editableMap[record.draw._id]">
            <a-input-number
              v-model:value="editableMap[record.draw._id].total"
              :min="0"
              :precision="0"
              style="width: 90px"
            />
          </template>
          <template v-else>
            <span>{{ record.total ?? 0 }}</span>
          </template>
        </template>
        <!-- 可编辑：概率（百分比） -->
        <template v-if="column.key === 'probability'">
          <template v-if="editableMap[record.draw._id]">
            <a-input-number
              v-model:value="editableMap[record.draw._id].probabilityPercent"
              :min="0"
              :max="100"
              :step="0.01"
              :formatter="percentFormatter"
              :parser="percentParser"
              style="width: 100px"
            />
          </template>
          <template v-else>
            <span>{{ ((record.probability ?? 0) * 100).toFixed(2) }}%</span>
          </template>
        </template>
        <!-- 可编辑：保底数 -->
        <template v-if="column.key === 'bottom_num'">
          <template v-if="editableMap[record.draw._id]">
            <a-input-number
              v-model:value="editableMap[record.draw._id].guarantee"
              :min="0"
              :precision="0"
              style="width: 90px"
            />
          </template>
          <template v-else>
            <span>{{ record.guarantee ?? 0 }}</span>
          </template>
        </template>
        <template v-if="column.key === 'action'">
          <a-button type="link" size="small" danger @click="handleUnCheck(record)">
            取消选中
          </a-button>
          <a-button type="link" size="small"  @click="handleUnSave(record)">
            保存
          </a-button>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { SubTypeEnum } from '@/utils/enumeration'
import type { ActivePoolItem } from '@/types/active.api'
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { updateActiveDrawConfig } from '@/api/active.api'

const prop = defineProps<{
  activeid: string
  tableList: ActivePoolItem[]
}>()
const emit = defineEmits(['handleOutSelectDrawList'])

// 每个奖品的可编辑状态（以 draw._id 为键）
const editableMap = ref<Record<string, { total: number; probabilityPercent: number; guarantee: number }>>({})

const initEditable = () => {
  const map: Record<string, { total: number; probabilityPercent: number; guarantee: number }> = {}
  prop.tableList.forEach((item: ActivePoolItem) => {
    const id = item.draw._id
    map[id] = {
      total: item.total ?? 0,
      probabilityPercent: (item.probability ?? 0) * 100,
      guarantee: item.guarantee ?? 0,
    }
  })
  editableMap.value = map
}

watch(
  () => prop.tableList,
  () => initEditable(),
  { immediate: true, deep: true },
)

// 百分比输入框格式化/解析
const percentFormatter = (value: string | number) => `${value}%`
const percentParser = (value: string) => (value || '').replace('%', '')

const columns = [
  {
    title: '奖品名称',
    key: 'name',
    customRender: ({ record }: { record: ActivePoolItem }) => record.draw?.name ?? '-',
  },
  {
    title: '奖品图片',
    dataIndex: 'pic',
    key: 'pic',
  },
  {
    title: '已消耗',
    key: 'use_num',
    width: 80,
    customRender: ({ record }: { record: ActivePoolItem }) => record.consumed ?? 0,
  },
  {
    title: '总数量',
    key: 'num',
    width: 80,
    customRender: ({ record }: { record: ActivePoolItem }) => record.total ?? 0,
  },
  {
    title: '概率',
    key: 'probability',
    width: 80,
    customRender: ({ record }: { record: ActivePoolItem }) => `${((record.probability ?? 0) * 100).toFixed(2)}%`,
  },
  {
    title: '保底数',
    key: 'bottom_num',
    width: 80,
    customRender: ({ record }: { record: ActivePoolItem }) => record.guarantee ?? 0,
  },
  {
    title: '价值',
    key: 'price',
    width: 80,
    customRender: ({ record }: { record: ActivePoolItem }) => `¥${(((record.draw?.price ?? 0)) / 100).toFixed(2)}`,
  },
  {
    title: '奖品标签',
    dataIndex: 'subTitle',
    key: 'subTitle',
    with: 80,
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 80,
  },
]

const handleUnCheck = async (_record: ActivePoolItem) => {
  emit('handleOutSelectDrawList', _record)
}

const handleUnSave = async (_record: ActivePoolItem) => {
  const id = prop.activeid
  const drawId = _record.draw._id
  const edit = editableMap.value[drawId]
  if (!edit) {
    return message.error('未找到当前行的可编辑数据')
  }
  try {
    const { code, message: msg } = await updateActiveDrawConfig(id, drawId, {
      total: edit.total,
      probability: (Number(edit.probabilityPercent) || 0) / 100,
      guarantee: edit.guarantee,
    })
    if (code === 200) {
      // 同步行内显示数据
      _record.total = edit.total
      _record.probability = (Number(edit.probabilityPercent) || 0) / 100
      _record.guarantee = edit.guarantee
      message.success('保存成功')
    } else {
      message.error(msg || '保存失败')
    }
  } catch (err) {
    console.error(err)
    message.error('保存失败')
  }
}
</script>

<style scoped>
.table-container {
  padding: 10px;
}
</style>
